package com.leo.snake;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class GamePanel extends JPanel {
    Snake snake;//蛇
    Food food;//食物
    Thread th;//控制蛇的线程
    int FPS=5;//每秒蛇的移动速度。

    public GamePanel() {
        //初始化蛇和食物
        snake = new Snake();
        food = new Food(snake);
        //获取焦点。监听键盘按键
        setFocusable(true);
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                snake.event(e.getKeyChar());
            }
        });
        //创建线程，定时控制蛇的移动
        th = new Thread(() -> {
            while (true) {
                int res = snake.move(food);
                //如果move方法返回1，说明吃到了食物，就调用食物的reset方法重置食物位置
                if (res == 1) food.reset(snake.x, snake.y);
                else if (res == 2) {
                    //如果move方法返回2，说明自己咬到自己了，弹出游戏结束提示框并显示成绩，然后重新开始游戏
                    JOptionPane.showConfirmDialog(null, "游戏结束，得分:" + (snake.len - 3), "GAME OVER", JOptionPane.YES_OPTION);
                    snake = new Snake();
                    food = new Food(snake);
                }else if(res==3){
                    JOptionPane.showConfirmDialog(null, "游戏胜利，得分:" + (snake.len - 3), "VICTORY", JOptionPane.YES_OPTION);
                    snake = new Snake();
                    food = new Food(snake);
                }
                try {
                    //sleep的时间直接影响到蛇的“速度”
                    Thread.sleep(1000/FPS);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        th.start();
    }

    /**
     * 将蛇、食物画到面板上
     *
     * @param g
     */
    @Override
    public void paint(Graphics g) {
        g.clearRect(0, 0, getWidth(), getHeight());
        //在顶部画一条线，区分游戏区域
        g.drawLine(0, 0, getWidth(), 0);
        snake.draw(g);
        food.draw(g);
        repaint();
    }
}
